/*
 * Administracio.java
 *
 */

package org.wooxes.client;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DisclosureEvent;
import com.google.gwt.user.client.ui.DisclosureHandler;
import com.google.gwt.user.client.ui.DisclosurePanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.Window;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;

import org.gwtwidgets.client.util.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

/**
 *
 * @author woox
 */
public class Administracio extends Sink {
    
    public static SinkInfo init() {
        return new SinkInfo("Administració", "Administració") {
            public Sink createInstance() {
                return new Administracio();
            }
        };
    }

    final String TXT_ERROR_BD = "Error: No es pot conectar amb la base de dades";
    final String TXT_LOADING = "Carregant...";
    Label lblcarregant;
    
    Label lbl_anuncis = new Label("Anuncis");
    Label lbl_assignatures = new Label("Assignatures / Activitats");
    Label lbl_configuracio = new Label("Configuració");
    Label lbl_integritat = new Label("Integritat Arxius - BD");
    
    SimplePanel contenedor;
    

    public Administracio() {
        VerticalPanel vp = new VerticalPanel();
        vp.setWidth("100%");
        
        lblcarregant = new Label(TXT_LOADING);
        lblcarregant.setStyleName("Label-Carregant");
        
        contenedor = new SimplePanel();
        contenedor.setStyleName("Contenedor");
        
        HorizontalPanel menu = new HorizontalPanel();
        menu.setStyleName("Admin-Menu-hp");
        
        lbl_anuncis.setStyleName("Admin-Menu");
        lbl_anuncis.addClickListener(new ClickListener(){
            public void onClick(Widget sender){
                lblcarregant.setVisible(true);
                getAnuncisService().getAnuncis(mostrarAnuncis());
            } 
        });
        
        lbl_assignatures.setStyleName("Admin-Menu");
        lbl_assignatures.addClickListener(new ClickListener(){
            public void onClick(Widget sender){
                lblcarregant.setVisible(true);
                //getService().getConfiguracio(mostrarAssignatures());
                getActivitatsService().getAssignatures(mostrarAssignatures());
                
            } 
        });
        
        lbl_configuracio.setStyleName("Admin-Menu");
        lbl_configuracio.addClickListener(new ClickListener(){
            public void onClick(Widget sender){
                lblcarregant.setVisible(true);
                getService().getConfiguracio(mostrarConfiguracio());
            } 
        });

        menu.add(lbl_anuncis);
        menu.add(lbl_assignatures);
        menu.add(lbl_configuracio);
        
        vp.add(menu);
        vp.add(lblcarregant);
        vp.add(contenedor);
        initWidget(vp);
        getAnuncisService().getAnuncis(mostrarAnuncis());
    }

    private AsyncCallback mostrarAnuncis(){
        return new AsyncCallback() {
            public void onSuccess(Object result){
                if(result == null){
                    lblcarregant.setVisible(false);
                    contenedor.setWidget(new Label(TXT_ERROR_BD));
                    return;
                }
                
                VerticalPanel vp = new VerticalPanel();
                vp.setWidth("100%");

                Label lbl_crea = new Label("Crea un nou anunci");
                lbl_crea.setStyleName("link");
                lbl_crea.addClickListener(new ClickListener(){
                    public void onClick(Widget sender){
                        final TransparentDialogBox dialog = new TransparentDialogBox();
                        dialog.setText("Crear anunci");

                        final FormPanel fp = new FormPanel();
                        fp.setAction("crear_anunci_servlet");
                        fp.setMethod(FormPanel.METHOD_POST);
                        fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                        fp.addFormHandler(new FormHandler(){
                            public void onSubmit(FormSubmitEvent event){
                                //Realitzar comprovacions
                            }
                            public void onSubmitComplete(FormSubmitCompleteEvent event){
                                String resposta = event.getResults();
                                if (!resposta.startsWith("ok")){
                                    Window.alert(resposta);
                                }
                                lblcarregant.setVisible(true);
                                getAnuncisService().getAnuncis(mostrarAnuncis());
                                dialog.hide();
                            }
                        });

                        VerticalPanel vp = new VerticalPanel();
                        vp.addStyleName("padding10");
                        vp.setWidth("350px");

                        // Titol
                        Label textTitol = new Label("Titol:");
                        final TextBox boxTitol = new TextBox();
                        boxTitol.setName("titol");
                        boxTitol.setMaxLength(50);
                        HorizontalPanel hpTitol = new HorizontalPanel();
                        hpTitol.add(textTitol);
                        hpTitol.setCellWidth(textTitol, "50%");
                        hpTitol.add(boxTitol);
                        hpTitol.setCellWidth(boxTitol, "50%");

                        // Text
                        Label textDescripcio = new Label("Text:");
                        final TextArea boxDescripcio = new TextArea();
                        boxDescripcio.setName("descripcio");
                        HorizontalPanel hpDescripcio = new HorizontalPanel();
                        hpDescripcio.add(textDescripcio);
                        hpDescripcio.add(boxDescripcio);

                        Button enviar = new Button("Crea");
                        enviar.addClickListener(new ClickListener(){
                            public void onClick(Widget sender){
                                fp.submit();
                            }
                        });
                        Button cancel = new Button("Cancel·la");
                        cancel.addClickListener(new ClickListener(){
                            public void onClick(Widget sender){
                                dialog.hide();
                            }
                        });
                        HorizontalPanel hpButton = new HorizontalPanel();
                        hpButton.add(enviar);
                        hpButton.add(cancel);
                        vp.add(hpTitol);
                        vp.add(hpDescripcio);
                        vp.add(hpButton);
                        fp.setWidget(vp);
                        dialog.setWidget(fp);
                        dialog.show();
                    }
                });

                HorizontalPanel hp_crea = new HorizontalPanel();
                hp_crea.add(lbl_crea);
                
                FlexTable flex = new FlexTable();
                flex.setStyleName("Anuncis-FlexTable");
                
                flex.setWidget(0, 0, new Label("Anuncis"));
                flex.getFlexCellFormatter().setColSpan(0, 0, 3);
                flex.getRowFormatter().setStyleName(0, "Anuncis-FlexTable-Header");

                Vector v = (Vector) result;
                final int index = 1;
                for ( int i=0; i<v.size(); i++ ){
                    final Anunci a = (Anunci) v.get(i);

                    flex.setWidget(index + i, 0, new Label(a.getTitol()));

                    final Label lblEditar = new Label("Edita");
                    lblEditar.setStyleName("link");
                    lblEditar.addClickListener(new ClickListener(){
                        public void onClick(Widget sender){
                            final TransparentDialogBox dialog = new TransparentDialogBox();
                            dialog.setText("Editar anunci");

                            final FormPanel fp = new FormPanel();
                            fp.setAction("modificar_anunci_servlet");
                            fp.setMethod(FormPanel.METHOD_POST);
                            fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                            fp.addFormHandler(new FormHandler(){
                                public void onSubmit(FormSubmitEvent event){
                                    //Realitzar comprovacions
                                }
                                public void onSubmitComplete(FormSubmitCompleteEvent event){
                                    String resposta = event.getResults();
                                    if (!resposta.startsWith("ok")){
                                        Window.alert(resposta);
                                    }
                                    lblcarregant.setVisible(true);
                                    getAnuncisService().getAnuncis(mostrarAnuncis());
                                    dialog.hide();
                                }
                            });

                            VerticalPanel vp = new VerticalPanel();
                            vp.addStyleName("padding10");
                            vp.setWidth("350px");

                            Hidden hiddenId = new Hidden("id", Integer.toString(a.getId()));

                            // Titol
                            Label textTitol = new Label("Titol:");
                            final TextBox boxTitol = new TextBox();
                            boxTitol.setName("titol");
                            boxTitol.setText(a.getTitol());
                            boxTitol.setMaxLength(50);
                            HorizontalPanel hpTitol = new HorizontalPanel();
                            hpTitol.add(textTitol);
                            hpTitol.add(boxTitol);

                            // Data
                            Label textData = new Label("Última modificació:");
                            final TextBox boxData = new TextBox();
                            boxData.setReadOnly(true);
                            boxData.setName("data");
                            boxData.setText(a.getFormattedData());
                            HorizontalPanel hpData = new HorizontalPanel();
                            hpData.add(textData);
                            hpData.add(boxData);

                            // Text
                            Label textDescripcio = new Label("Text:");
                            final TextArea boxDescripcio = new TextArea();
                            boxDescripcio.setName("descripcio");
                            boxDescripcio.setText(a.getText());
                            HorizontalPanel hpDescripcio = new HorizontalPanel();
                            hpDescripcio.add(textDescripcio);
                            hpDescripcio.add(boxDescripcio);

                            Button enviar = new Button("Modifica");
                            enviar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    fp.submit();
                                }
                            });
                            Button cancel = new Button("Cancel·la");
                            cancel.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    dialog.hide();
                                }
                            });
                            
                            HorizontalPanel hpButton = new HorizontalPanel();
                            hpButton.add(enviar);
                            hpButton.add(cancel);
                            vp.add(hiddenId);
                            vp.add(hpTitol);
                            vp.add(hpDescripcio);
                            vp.add(hpData);
                            vp.add(hpButton);
                            fp.setWidget(vp);
                            dialog.setWidget(fp);
                            dialog.show();
                        }
                    });
                    // Es fica dins un HorizontalPanel per evitar que el link ocupi tota la cel·la
                    HorizontalPanel hpEditar = new HorizontalPanel();
                    hpEditar.add(lblEditar);

                    Label lblEliminar = new Label("Elimina");
                    lblEliminar.setStyleName("link");
                    lblEliminar.addClickListener(new ClickListener(){
                        public void onClick(Widget sender){
                            final TransparentDialogBox dialog = new TransparentDialogBox();
                            dialog.setText("Eliminar anunci");
                            final FormPanel fp = new FormPanel();
                            fp.setAction("eliminar_anunci_servlet");
                            fp.setMethod(FormPanel.METHOD_POST);
                            fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                            fp.addFormHandler(new FormHandler(){
                                public void onSubmit(FormSubmitEvent event){
                                    //Realitzar comprovacions
                                }
                                public void onSubmitComplete(FormSubmitCompleteEvent event){
                                    String resposta = event.getResults();
                                    if (!resposta.startsWith("ok")){
                                        Window.alert(resposta);
                                    }
                                    lblcarregant.setVisible(true);
                                    getAnuncisService().getAnuncis(mostrarAnuncis());
                                    dialog.hide();
                                }
                            });
                            
                            VerticalPanel vp = new VerticalPanel();
                            vp.setWidth("350px");
                            vp.addStyleName("padding10");
                            Hidden hiddenId = new Hidden("id", Integer.toString(a.getId()));
                            HTML text = new HTML(
                                    "Si borreu aquest anunci, després no es podrà recuperar." +
                                    "<p>Voleu eliminar l'anunci:<br /><center>\"" + a.getTitol() + "\" ?</center></p>");
                            Button buttonAceptar = new Button("Elimina");
                            buttonAceptar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    fp.submit();
                                }
                            });
                            Button buttonCancelar = new Button("Cancel·la");
                            buttonCancelar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    dialog.hide();
                                }
                            });
                            
                            HorizontalPanel hpButton = new HorizontalPanel();
                            hpButton.add(buttonAceptar);
                            hpButton.add(buttonCancelar);
                            
                            vp.add(hiddenId);
                            vp.add(text);
                            vp.add(hpButton);
                            fp.setWidget(vp);
                            dialog.setWidget(fp);
                            dialog.show();
                        }
                    });
                    // Es fica dins un HorizontalPanel per evitar que el link ocupi tota la cel·la
                    HorizontalPanel hpEliminar = new HorizontalPanel();
                    hpEliminar.add(lblEliminar);
                    
                    flex.setWidget(index + i, 1, hpEditar);
                    flex.setWidget(index + i, 2, hpEliminar);

                    flex.getFlexCellFormatter().setWidth(index + i, 1, "20%");
                    flex.getFlexCellFormatter().setWidth(index + i, 2, "20%");
                }
                vp.add(hp_crea);
                vp.add(flex);
                
                inicialitzarEstils(lbl_anuncis);
                lblcarregant.setVisible(false);
                
                contenedor.setWidget(vp);
            }
            
            public void onFailure(Throwable caught){
                onSuccess(null);
            }
        };
    }
    
    private AsyncCallback mostrarAssignatures(){
        return new AsyncCallback() {
            public void onSuccess(Object result){
                Vector v = (Vector) result;
                if( v == null ){
                    lblcarregant.setVisible(false);
                    contenedor.setWidget(new Label("Error carregant Assignatures / Activitats"));
                    return;
                }

                VerticalPanel vp = new VerticalPanel();
                vp.setWidth("100%");
                
                // Formulari
                final FormPanel fpCrearAssignatura = new FormPanel();
                fpCrearAssignatura.setAction("crear_assignatura_servlet");
                fpCrearAssignatura.setMethod(FormPanel.METHOD_POST);
                fpCrearAssignatura.setEncoding(FormPanel.ENCODING_URLENCODED);
                
                
                // Etiqueta
                Label lblCrearAssignatura = new Label("Crea una Assignatura nova:");
                lblCrearAssignatura.addStyleName("Assignatures-lblCrearAssignatura");
                
                // TextBox
                final TextBox boxCrearAssignatura = new TextBox();
                boxCrearAssignatura.setName("nom");
                
                // Botó
                Button btnCrearAssignatura = new Button("Crea");
                btnCrearAssignatura.addClickListener(new ClickListener(){
                    public void onClick(Widget sender){
                        fpCrearAssignatura.submit();
                    }
                });
                
                
                // S'afegeixen els camps al formulari, dins els seus panels
                VerticalPanel vpCrearAssignatura = new VerticalPanel();
                vpCrearAssignatura.add(lblCrearAssignatura);
                
                HorizontalPanel hpCrearAssignatura = new HorizontalPanel();
                hpCrearAssignatura.add(boxCrearAssignatura);
                hpCrearAssignatura.add(btnCrearAssignatura);
                
                vpCrearAssignatura.add(hpCrearAssignatura);
                
                fpCrearAssignatura.setWidget(vpCrearAssignatura);
                
                // Comprovacions
                fpCrearAssignatura.addFormHandler(new FormHandler(){
                    public void onSubmit(FormSubmitEvent event){
                        //Realitzar comprovacions
                        if( boxCrearAssignatura.getText().length() == 0 ){
                            Window.alert("Nom buit");
                            event.setCancelled(true);
                        }
                    }
                    public void onSubmitComplete(FormSubmitCompleteEvent event){
                        String resposta = event.getResults();
                        if (!resposta.startsWith("ok")){
                            Window.alert(resposta);
                        }
                        getActivitatsService().getAssignatures(mostrarAssignatures());
                    }

                });
                
                
                // S'afegeix el formulari per crear nova Assignatura
                vp.add(fpCrearAssignatura);
                
                FlexTable flex = new FlexTable();
                flex.setStyleName("Anuncis-FlexTable");
                
                flex.setWidget(0, 0, new Label("Assignatures / Activitats"));
                flex.getFlexCellFormatter().setColSpan(0, 0, 4);
                flex.getRowFormatter().setStyleName(0, "Anuncis-FlexTable-Header");
                
                final int index = 1;
                
                for ( int i=0; i<v.size(); i++ ){
                    final Assignatura as = (Assignatura) v.get(i);
                    
                    ImageDir imatge = new ImageDir();
                    imatge.setStyleName("link");
                    imatge.addClickListener(new ClickListener(){
                        public void onClick(Widget sender) {
                            ImageDir img = (ImageDir) sender;
                            FlexTable flex = (FlexTable) img.getParent();
                            int index2 = img.getIndex();                                    
                            if(!img.isOpen()){
                                img.setOpen(true);
                                lblcarregant.setVisible(true);

                                getService().getActivitats(
                                        as.getId(),
                                        mostrarActivitats(flex, index2, as.getId()));
                                }
                            else{
                                img.setOpen(false);
                                Widget aux = null;
                                borrarActivitats(flex,index2);
                            }
                        }
                    });
                    flex.setWidget(index + i, 0, imatge);
                    flex.setWidget(index + i, 1, new Label(as.getNom()));

                    final Label lblEditar = new Label("Canvia el nom");
                    lblEditar.setStyleName("link");
                    lblEditar.addClickListener(new ClickListener(){
                        public void onClick(Widget sender){
                            final TransparentDialogBox dialog = new TransparentDialogBox();
                            dialog.setText("Canvia el nom de l'assignatura");
                            
                            final FormPanel fp = new FormPanel();
                            fp.setAction("modificar_assignatura_servlet");
                            fp.setMethod(FormPanel.METHOD_POST);
                            fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                            fp.addFormHandler(new FormHandler(){
                                public void onSubmit(FormSubmitEvent event){
                                    //Realitzar comprovacions
                                }
                                public void onSubmitComplete(FormSubmitCompleteEvent event){
                                    String resposta = event.getResults();
                                    if (!resposta.startsWith("ok")){
                                        Window.alert(resposta);
                                    }
                                    lblcarregant.setVisible(true);
                                    getActivitatsService().getAssignatures(mostrarAssignatures());
                                    dialog.hide();
                                }
                            });
                            
                            VerticalPanel vp = new VerticalPanel();
                            vp.setWidth("350px");
                            vp.addStyleName("padding10");

                            Hidden hiddenId = new Hidden("id", Integer.toString(as.getId()));
                            
                            Label text = new Label("Indiqueu un nom nou:");
                            final TextBox box = new TextBox();
                            box.setName("nom");
                            box.setText(as.getNom());
                            HorizontalPanel hpNom = new HorizontalPanel();
                            hpNom.add(text);
                            hpNom.add(box);
                            
                            Button enviar = new Button("Modifica");
                            enviar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    fp.submit();
                                }
                            });
                            Button cancel = new Button("Cancel·la");
                            cancel.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    dialog.hide();
                                }
                            });
                            HorizontalPanel hpButton = new HorizontalPanel();
                            hpButton.add(enviar);
                            hpButton.add(cancel);

                            vp.add(hiddenId);
                            vp.add(hpNom);
                            vp.add(hpButton);
                            fp.setWidget(vp);
                            dialog.setWidget(fp);
                            dialog.show();
                        }
                    });

                    // Es fica dins un HorizontalPanel per evitar que el link ocupi tota la cel·la
                    HorizontalPanel hpEditar = new HorizontalPanel();
                    hpEditar.add(lblEditar);
                    
                    flex.setWidget(index + i, 2, hpEditar);

                    Label lblEliminar = new Label("Elimina");
                    lblEliminar.setStyleName("link");
                    lblEliminar.addClickListener(new ClickListener(){
                        public void onClick(Widget sender){
                            final TransparentDialogBox dialog = new TransparentDialogBox();
                            dialog.setText("Eliminar assignatura");
                            final FormPanel fp = new FormPanel();
                            fp.setAction("eliminar_assignatura_servlet");
                            fp.setMethod(FormPanel.METHOD_POST);
                            fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                            fp.addFormHandler(new FormHandler(){
                                public void onSubmit(FormSubmitEvent event){
                                    //Realitzar comprovacions
                                }
                                public void onSubmitComplete(FormSubmitCompleteEvent event){
                                    String resposta = event.getResults();
                                    if (!resposta.startsWith("ok")){
                                        Window.alert(resposta);
                                    }
                                    lblcarregant.setVisible(true);
                                    getActivitatsService().getAssignatures(mostrarAssignatures());
                                    dialog.hide();
                                }
                            });
                            
                            VerticalPanel vp = new VerticalPanel();
                            vp.setWidth("350px");
                            vp.addStyleName("padding10");
                            
                            Hidden hiddenId = new Hidden("id", Integer.toString(as.getId()));
                            HTML text = new HTML(
                                    "Si borreu aquesta assignatura, també es borraran les activitats " +
                                    "i entregues que aquesta conté." +
                                    "<p>Voleu eliminar l'assignatura:<br /><center>\"" + as.getNom() + "\" ?</center></p>");
                            Button buttonAceptar = new Button("Elimina");
                            buttonAceptar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    fp.submit();
                                }
                            });
                            Button buttonCancelar = new Button("Cancel·la");
                            buttonCancelar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    dialog.hide();
                                }
                            });
                            
                            HorizontalPanel hpButton = new HorizontalPanel();
                            hpButton.add(buttonAceptar);
                            hpButton.add(buttonCancelar);
                            
                            vp.add(hiddenId);
                            vp.add(text);
                            vp.add(hpButton);
                            fp.setWidget(vp);
                            dialog.setWidget(fp);
                            dialog.show();
                        }
                    });
                    // Es fica dins un HorizontalPanel per evitar que el link ocupi tota la cel·la
                    HorizontalPanel hpEliminar = new HorizontalPanel();
                    hpEliminar.add(lblEliminar);
                    flex.setWidget(index + i, 3, hpEliminar);
                    flex.getFlexCellFormatter().setWidth(index + i, 0, "25px");
                    flex.getFlexCellFormatter().setWidth(index + i, 2, "20%");
                    flex.getFlexCellFormatter().setWidth(index + i, 3, "20%");
                }
                vp.add(flex);

                inicialitzarEstils(lbl_assignatures);
                lblcarregant.setVisible(false);
                
                contenedor.setWidget(vp);
            }
            
            public void onFailure(Throwable caught){
                onSuccess(null);
            }
        };
    }
    
    private AsyncCallback mostrarConfiguracio(){
        return new AsyncCallback() {
            public void onSuccess(Object result) {
                if(result == null){
                    lblcarregant.setVisible(false);
                    contenedor.setWidget(new Label("Error carregant Configuració"));
                    return;
                }
                Configuracio config = (Configuracio) result;
                VerticalPanel vp = new VerticalPanel();

                vp.setStyleName("Opcions-Contingut");
                vp.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);

                vp.add(crearPanelConfiguracio("UploadDir", config.getUploadDir(),
                        "En aquesta carpeta es guardaran els arxius enviats per els usuaris.<br />" +
                        "Acabar la ruta amb / (Linux) o \\ (Windows)."));
                vp.add(crearPanelConfiguracio("MaxFileSize", Integer.toString(config.getMaxFileSize()),
                        "Tamany màxim dels arxius enviats per els usuaris. En KB."));

                lblcarregant.setVisible(false);
                inicialitzarEstils(lbl_configuracio);
                contenedor.setWidget(vp);
            }
            public void onFailure(Throwable caught) {
                onSuccess(null);
            }
        };
    }

    private Panel crearPanelConfiguracio(String a, final String b, String c){
        VerticalPanel vp = new VerticalPanel();
        SimplePanel sp1 = new SimplePanel();
        DisclosurePanel dp = new DisclosurePanel();
        HorizontalPanel hp1 = new HorizontalPanel();
        SimplePanel sp2 = new SimplePanel();

        // Nom
        Label label = new Label(a);
        label.setStyleName("Opcions-Nom");
        sp1.add(label);
        sp1.setStyleName("Opcions-HorizontalDalt-SimplePanel");
        
        // Valor
        dp.setStylePrimaryName("Opcions-Disclosure");
        Label nom = new Label(b);
        nom.setStyleName("Opcions-Disclosure-Header");
        dp.setHeader(nom);

        // Enviar nou valor -> Formulari
        HorizontalPanel content = new HorizontalPanel();
        content.setStyleName("Opcions-Disclosure-Content");
        
        final FormPanel form = new FormPanel();
        form.setAction("opcionsservlet");
        form.setMethod(FormPanel.METHOD_POST);

        final Hidden nom_opcio = new Hidden("nom",a.toLowerCase());
        content.add(nom_opcio);
        final TextBox box = new TextBox();
        box.setName("valor");
        box.setVisibleLength(20);
        content.add(box);
        
        // Enviar nou valor -> Imatge
        Image enviar = new Image("images/enviar.gif");
        enviar.setStyleName("link");
        enviar.addClickListener(new ClickListener(){
            public void onClick(Widget sender){
                form.submit();
            }
        });

        content.add(enviar);
        content.setCellHorizontalAlignment(enviar,HorizontalPanel.ALIGN_RIGHT);
        content.setCellVerticalAlignment(enviar,HorizontalPanel.ALIGN_MIDDLE);
        
        // Al enviar el formulari
        form.addFormHandler(new FormHandler(){
            public void onSubmit(FormSubmitEvent event){
                if(box.getText().equals("")){
                    Window.alert("Error: No s'ha introduit cap valor");
                    event.setCancelled(true);
                    return;
                }
                if(nom_opcio.getValue().equals("maxfilesize")){
                    try {
                        Integer.parseInt(box.getText());
                        }
                    catch (NumberFormatException nfe){
                        event.setCancelled(true);
                        Window.alert("Error: S'ha d'introduir un nombre enter");
                    }
                }
                else if(nom_opcio.getValue().equals("uploaddir")){
                    if( !box.getText().endsWith("/") && !box.getText().endsWith("\\")){
                        Window.alert("Error: La ruta ha d'acabar amb / (Linux) o \\ (Windows)");
                        event.setCancelled(true);
                        return;
                    }
                }
                
                //Si no es cancela l'enviament de dades, es mostra l'etiqueta "Carregant..."
                if(!event.isCancelled()){
                    lblcarregant.setVisible(true);
                }
            }
            public void onSubmitComplete(FormSubmitCompleteEvent event){
                lblcarregant.setVisible(false);
                Image imatge;
                String resposta = event.getResults();
                if (resposta.startsWith("ok:")){
                    //lblcarregant.setVisible(false);
                    /*resposta = resposta.substring(3);
                    nom.setText(resposta);
                    dp.setOpen(false);
                    box.setText("");*/
                    getService().getConfiguracio(mostrarConfiguracio());
                }
                else{
                    Window.alert(resposta);
                }
            }
        });
        
        form.setWidget(content);
        
        // Al mostrar el camp de text, el valor per defecte serà "b"
        // és a dir, el valor actual
        dp.addEventHandler(new DisclosureHandler(){
            public void onClose(DisclosureEvent event){
            }
            public void onOpen(DisclosureEvent event){
                box.setText(b);
            }
        });
        dp.setContent(form);
        
        // Comentaris
        HTML comment = new HTML(c);
        comment.setStyleName("Opcions-Comentaris");
        sp2.add(comment);
        
        // Estils i afegir als panels
        hp1.setStyleName("Opcions-HorizontalDalt");
        sp2.setStyleName("Opcions-HorizontalBaix");
        vp.setStyleName("Opcions-Vertical");
        
        hp1.add(sp1);
        hp1.add(dp);
        vp.add(hp1);
        vp.add(sp2);
        
        return vp;
    }
    
    private AsyncCallback mostrarActivitats(final FlexTable flex, final int s_indice, final int s_id){
        return new AsyncCallback() {
            public void onSuccess(Object result) {
                Vector v = (Vector) result;
                int index = s_indice + 1;
                if( v == null){
                    flex.insertRow(index);
                    Label label = new Label(TXT_ERROR_BD);
                    flex.setWidget(index, 1, label);
                    lblcarregant.setVisible(false);
                    return;
                }
                
                final Label lblCrear = new Label("Crea una Activitat nova");
                lblCrear.setStyleName("link");
                lblCrear.addClickListener(new ClickListener(){
                    public void onClick(Widget sender){
                        final TransparentDialogBox dialog = new TransparentDialogBox();
                        dialog.setText("Crear activitat");

                        final FormPanel fp = new FormPanel();
                        fp.setAction("crear_activitat_servlet");
                        fp.setMethod(FormPanel.METHOD_POST);
                        fp.setEncoding(FormPanel.ENCODING_MULTIPART);
                        fp.addFormHandler(new FormHandler(){
                            public void onSubmit(FormSubmitEvent event){
                                //Realitzar comprovacions
                            }
                            public void onSubmitComplete(FormSubmitCompleteEvent event){
                                String resposta = event.getResults();
                                if (!resposta.startsWith("ok")){
                                    Window.alert(resposta);
                                }
                                lblcarregant.setVisible(true);
                                borrarActivitats(flex,s_indice);
                                getService().getActivitats(
                                    s_id,
                                    mostrarActivitats(flex, s_indice, s_id));
                                //getActivitatsService().getAssignatures(mostrarAssignatures());
                                dialog.hide();
                            }
                        });

                        VerticalPanel vp = new VerticalPanel();
                        vp.setWidth("350px");
                        vp.addStyleName("padding10");

                        Hidden hiddenId = new Hidden("id", Integer.toString(s_id));
                        
                        // Nom
                        Label textNom = new Label("Nom:");
                        final TextBox boxNom = new TextBox();
                        boxNom.setName("nom");

                        HorizontalPanel hpNom = new HorizontalPanel();
                        hpNom.add(textNom);
                        hpNom.add(boxNom);

                        // Data
                        Label textData = new Label("Data: (dd-mm-yyyy)");
                        final TextBox boxData = new TextBox();
                        boxData.setName("data");
                        boxData.setMaxLength(10);
                        HorizontalPanel hpData = new HorizontalPanel();
                        hpData.add(textData);
                        hpData.add(boxData);

                        // Hora
                        Label textHora = new Label("Hora: (hh:mm:ss)");
                        final TextBox boxHora = new TextBox();
                        boxHora.setName("hora");
                        boxHora.setMaxLength(8);
                        //SimpleDateFormat formatHora = new SimpleDateFormat("HH:mm:ss");
                        //boxHora.setText(formatHora.format(ac.getData()));
                        HorizontalPanel hpHora = new HorizontalPanel();
                        hpHora.add(textHora);
                        hpHora.add(boxHora);

                        // Descripcio
                        Label textDescripcio = new Label("Descripció:");
                        final TextArea boxDescripcio = new TextArea();
                        boxDescripcio.setName("descripcio");
                        //boxDescripcio.setText(ac.getDescripcio());
                        HorizontalPanel hpDescripcio = new HorizontalPanel();
                        hpDescripcio.add(textDescripcio);
                        hpDescripcio.add(boxDescripcio);
                        
                        Label textUpload = new Label("Arxiu:");
                        final FileUpload boxUpload = new FileUpload();
                        boxUpload.setName("file");

                        HorizontalPanel hpUpload = new HorizontalPanel();
                        hpUpload.add(textUpload);
                        hpUpload.add(boxUpload);
                        
                        Button enviar = new Button("Crea");
                        enviar.addClickListener(new ClickListener(){
                            public void onClick(Widget sender){
                                fp.submit();
                            }
                        });
                        Button cancel = new Button("Cancel·la");
                        cancel.addClickListener(new ClickListener(){
                            public void onClick(Widget sender){
                                dialog.hide();
                            }
                        });
                        HorizontalPanel hp = new HorizontalPanel();
                        hp.add(enviar);
                        hp.add(cancel);
                        vp.add(hiddenId);
                        vp.add(hpNom);
                        vp.add(hpData);
                        vp.add(hpHora);
                        vp.add(hpDescripcio);
                        vp.add(hpUpload);
                        vp.add(hp);
                        fp.setWidget(vp);
                        dialog.setWidget(fp);
                        dialog.show();
                    }
                });
                
                HorizontalPanel hpCrear = new HorizontalPanel();
                hpCrear.add(lblCrear);
                flex.insertRow(index);
                flex.setWidget(index, 1, hpCrear);
                //flex.setWidget(index, 1, fpCrearActivitat);
                index++;
                
                for(int i=0; i< v.size(); i++){
                    final Activitat ac = (Activitat) v.get(i);

                    Label nom = new Label(ac.getNom());



                    flex.insertRow(index + i);
                    flex.setWidget(index + i, 1, nom);

                    final Label lblEditar = new Label("Edita");
                    lblEditar.setStyleName("link");
                    lblEditar.addClickListener(new ClickListener(){
                        public void onClick(Widget sender){
                            final TransparentDialogBox dialog = new TransparentDialogBox();
                            dialog.setText("Editar activitat");

                            final FormPanel fp = new FormPanel();
                            fp.setAction("modificar_activitat_servlet");
                            fp.setMethod(FormPanel.METHOD_POST);
                            fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                            fp.addFormHandler(new FormHandler(){
                                public void onSubmit(FormSubmitEvent event){
                                    //Realitzar comprovacions
                                }
                                public void onSubmitComplete(FormSubmitCompleteEvent event){
                                    String resposta = event.getResults();
                                    if (!resposta.startsWith("ok")){
                                        Window.alert(resposta);
                                    }
                                    lblcarregant.setVisible(true);
                                    borrarActivitats(flex,s_indice);
                                    getService().getActivitats(
                                        s_id,
                                        mostrarActivitats(flex, s_indice, s_id));
                                    //getActivitatsService().getAssignatures(mostrarAssignatures());
                                    dialog.hide();
                                }
                            });

                            VerticalPanel vp = new VerticalPanel();
                            vp.setWidth("350px");
                            vp.addStyleName("padding10");

                            Hidden hiddenId = new Hidden("id", Integer.toString(ac.getId()));

                            // Nom
                            Label textNom = new Label("Nom:");
                            final TextBox boxNom = new TextBox();
                            boxNom.setName("nom");
                            boxNom.setText(ac.getNom());
                            HorizontalPanel hpNom = new HorizontalPanel();
                            hpNom.add(textNom);
                            hpNom.add(boxNom);

                            // Data
                            Label textData = new Label("Data: (dd-mm-yyyy)");
                            final TextBox boxData = new TextBox();
                            boxData.setName("data");
                            boxData.setMaxLength(10);
                            SimpleDateFormat formatData = new SimpleDateFormat("dd-MM-yyyy");
                            boxData.setText(formatData.format(ac.getData()));
                            HorizontalPanel hpData = new HorizontalPanel();
                            hpData.add(textData);
                            hpData.add(boxData);

                            // Hora
                            Label textHora = new Label("Hora: (hh:mm:ss)");
                            final TextBox boxHora = new TextBox();
                            boxHora.setName("hora");
                            boxHora.setMaxLength(8);
                            SimpleDateFormat formatHora = new SimpleDateFormat("HH:mm:ss");
                            boxHora.setText(formatHora.format(ac.getData()));
                            HorizontalPanel hpHora = new HorizontalPanel();
                            hpHora.add(textHora);
                            hpHora.add(boxHora);

                            // Descripcio
                            Label textDescripcio = new Label("Descripció:");
                            final TextArea boxDescripcio = new TextArea();
                            boxDescripcio.setName("descripcio");
                            boxDescripcio.setText(ac.getDescripcio());
                            HorizontalPanel hpDescripcio = new HorizontalPanel();
                            hpDescripcio.add(textDescripcio);
                            hpDescripcio.add(boxDescripcio);
                            
                            Label textArxiu = new Label("Arxiu:");
                            final TextBox boxArxiu = new TextBox();
                            boxArxiu.setName("arxiu");
                            boxArxiu.setText(ac.getAdjunt());
                            boxArxiu.setReadOnly(true);
                            HorizontalPanel hpArxiu = new HorizontalPanel();
                            hpArxiu.add(textArxiu);
                            hpArxiu.add(boxArxiu);
                            

                            Button enviar = new Button("Modifica");
                            enviar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    fp.submit();
                                }
                            });
                            Button cancel = new Button("Cancel·la");
                            cancel.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    dialog.hide();
                                }
                            });

                            HorizontalPanel hpButton = new HorizontalPanel();
                            hpButton.add(enviar);
                            hpButton.add(cancel);
                            
                            vp.add(hiddenId);
                            vp.add(hpNom);
                            vp.add(hpData);
                            vp.add(hpHora);
                            vp.add(hpDescripcio);
                            vp.add(hpArxiu);
                            vp.add(hpButton);
                            fp.setWidget(vp);
                            dialog.setWidget(fp);
                            dialog.show();
                        }
                    });

                    flex.setWidget(index + i, 2, lblEditar);

                    Label lblEliminar = new Label("Elimina");
                    lblEliminar.setStyleName("link");
                    lblEliminar.addClickListener(new ClickListener(){
                        public void onClick(Widget sender){
                            final TransparentDialogBox dialog = new TransparentDialogBox();
                            dialog.setText("Eliminar activitat");
                            final FormPanel fp = new FormPanel();
                            fp.setAction("eliminar_activitat_servlet");
                            fp.setMethod(FormPanel.METHOD_POST);
                            fp.setEncoding(FormPanel.ENCODING_URLENCODED);
                            fp.addFormHandler(new FormHandler(){
                                public void onSubmit(FormSubmitEvent event){
                                    //Realitzar comprovacions
                                }
                                public void onSubmitComplete(FormSubmitCompleteEvent event){
                                    String resposta = event.getResults();
                                    if (!resposta.startsWith("ok")){
                                        Window.alert(resposta);
                                    }
                                    lblcarregant.setVisible(true);
                                    borrarActivitats(flex,s_indice);
                                    getService().getActivitats(
                                        s_id,
                                        mostrarActivitats(flex, s_indice, s_id));
                                    //getActivitatsService().getAssignatures(mostrarAssignatures());
                                    dialog.hide();
                                }
                            });

                            VerticalPanel vp = new VerticalPanel();
                            vp.setWidth("350px");
                            vp.addStyleName("padding10");
                            
                            Hidden hiddenId = new Hidden("id", Integer.toString(ac.getId()));
                            HTML text = new HTML(
                                    "Si borreu aquesta activitat, també es borraran les " +
                                    "entregues que aquesta conté." +
                                    "<p>Voleu eliminar l'activitat:<br /><center>\"" + ac.getNom() + "\" ?</center></p>");
                            Button buttonAceptar = new Button("Elimina");
                            buttonAceptar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    fp.submit();
                                }
                            });
                            Button buttonCancelar = new Button("Cancel·la");
                            buttonCancelar.addClickListener(new ClickListener(){
                                public void onClick(Widget sender){
                                    dialog.hide();
                                }
                            });

                            HorizontalPanel hpButton = new HorizontalPanel();
                            hpButton.add(buttonAceptar);
                            hpButton.add(buttonCancelar);
                            vp.add(hiddenId);
                            vp.add(text);
                            vp.add(hpButton);
                            fp.setWidget(vp);
                            dialog.setWidget(fp);
                            dialog.show();
                        }
                    });

                    HorizontalPanel hpEliminar = new HorizontalPanel();
                    hpEliminar.add(lblEliminar);
                    flex.setWidget(index + i, 3, hpEliminar);
                }
                lblcarregant.setVisible(false);
            }
            public void onFailure(Throwable caught) {
                onSuccess(null);
            }
        };
    }
    
    // Borra les files que ja no s'han de mostrar
    // al amagar les entregues d'una activitat
    private int borrarActivitats (FlexTable flex, int index){
        int pos = index+1;
        int borrats = 0;
        boolean continuar = true;
        Widget aux;
        
        while(continuar && (pos < flex.getRowCount())){
            aux = flex.getWidget(pos, 0);
            if (aux == null){
                flex.removeRow(pos);
                borrats++;
            }
            else{
                continuar = false;
            }
        }
        return borrats;
    }
    
    private static AdministracioServiceAsync getService(){
        AdministracioServiceAsync service = (AdministracioServiceAsync) GWT.create(AdministracioService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        String moduleRelativeURL = GWT.getModuleBaseURL() + "administracio_service";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
        return service;
    }
    
    public static ActivitatsServiceAsync getActivitatsService(){
        ActivitatsServiceAsync service = (ActivitatsServiceAsync) GWT.create(ActivitatsService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        String moduleRelativeURL = GWT.getModuleBaseURL() + "activitatsservice";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
        return service;
    }
    
    private static AnuncisServiceAsync getAnuncisService(){
        AnuncisServiceAsync service = (AnuncisServiceAsync) GWT.create(AnuncisService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        String moduleRelativeURL = GWT.getModuleBaseURL() + "anuncis_service";
        endpoint.setServiceEntryPoint(moduleRelativeURL);
        return service;
    }
    
    private void inicialitzarEstils(Label label){
        lbl_anuncis.removeStyleName("Admin-Menu-Selected");
        lbl_assignatures.removeStyleName("Admin-Menu-Selected");
        lbl_configuracio.removeStyleName("Admin-Menu-Selected");
        lbl_integritat.removeStyleName("Admin-Menu-Selected");
        
        // S'aplica l'estil al menú seleccionat
        label.addStyleName("Admin-Menu-Selected");
    }

}
